package gas.backend.tac;

import java.util.ArrayList;

public class ICTac {
	
	public ArrayList<ICSymbol> symbolList = null;
	
	/*
	 * if token is NOT a number, return null
	 */
	private Number getNumber(String token) {
		String regex = "([0-9]+[.]?[0-9]*)|([0-9]*[.][0-9]+)";
		if(token.matches(regex)) {
			if(token.contains(".")) {
				return new Float(token);
			} else {
				return new Integer(token);
			}
		}
		return null;
	}
	
	
	private ICSymbol getSymbolFromString(String sToken) {
		if(sToken.equalsIgnoreCase("if") || sToken.equalsIgnoreCase("goto")) {
			return new ICSymbol(ICSymbolType.KEYWORD, sToken);
		}
		else if(sToken.equalsIgnoreCase("<") || sToken.equalsIgnoreCase("<=") || 
				sToken.equalsIgnoreCase("==") || sToken.equalsIgnoreCase(">=") || 
				sToken.equalsIgnoreCase(">")) {
			return new ICSymbol(ICSymbolType.CMPR_OP, sToken);
			
		}
		else if(sToken.equalsIgnoreCase("+") || sToken.equalsIgnoreCase("-") ||
				sToken.equalsIgnoreCase("*") || sToken.equalsIgnoreCase("/")){
			return new ICSymbol(ICSymbolType.ARIT_OP, sToken);
		}
		else if(sToken.equalsIgnoreCase("&&") || sToken.equalsIgnoreCase("||") ||
				sToken.equalsIgnoreCase("!")) {
			return new ICSymbol(ICSymbolType.BOOL_OP, sToken);
		}
		else ;if(sToken.contains("#")) {	// VAR'#'VAR, no space! just one '#'
			String[] tempTokens = sToken.split("#");
			
		}
		else if(sToken.matches("([0-9]+[.]?[0-9]*)|([0-9]*[.][0-9]+)")) {
			return new ICSymbol(ICSymbolType.NUM, getNumber(sToken));
		}
		else if(sToken.contains("_")) {
			String[] tempTokens = sToken.split("_");
			if(tempTokens[0].equalsIgnoreCase("var")) {
				return new ICSymbol(ICSymbolType.VAR, new Integer(tempTokens[1]));
			}
		}
		else if(sToken.equalsIgnoreCase("image")) {
			return new ICSymbol(ICSymbolType.TYPENAME, sToken);
		}
		else if(sToken.startsWith("$")) {
			return new ICSymbol(ICSymbolType.FILEPATH, sToken.substring(1));
		}
		return null;
	}
	
	public ICTac(String line) {
		symbolList = new ArrayList<ICSymbol>();
		String[] tokens = line.split(" ");
		for(int i = 0; i<tokens.length; i++) {
			symbolList.add(getSymbolFromString(tokens[i]));	
		}
	}
}
